package my.jwds.p31;

import java.util.Arrays;

public class NextPermutation {

    public static void main(String[] args) {
        NextPermutation obj = new NextPermutation();
        int [] nums = {4,2,0,2,3,2,0};
        obj.nextPermutation(nums);
        obj.nextPermutation1(nums);
        System.out.println(Arrays.toString(nums));
    }

    public void nextPermutation(int[] nums) {
        int swap1 = 0, swap2 = 0,length = nums.length;
        boolean flag = false;
        for (int i = length - 1; i > swap1; i--) {
            for (int j = i-1; j >= swap1; j--) {
                if (nums[i] > nums[j] && (!flag || swap1!= j ||  nums[i] < nums[swap2])){
                    swap1 = j;
                    swap2 = i;
                    flag = true;
                    break;
                }
            }
        }
        int temp = nums[swap2];
        nums[swap2] = nums[swap1];
        nums[swap1] = temp;

        if (!flag)swap1 =-1;
        for (int i = 1; i <= (length-swap1-1) /2; i++) {
            temp = nums[swap1+i];
            nums[swap1+i] = nums[length-i];
            nums[length-i] = temp;
        }

    }


    public void nextPermutation1(int[] nums) {
        int i = nums.length - 2;
        while (i >= 0 && nums[i] >= nums[i + 1]) {
            i--;
        }
        if (i >= 0) {
            int j = nums.length - 1;
            while (j >= 0 && nums[i] >= nums[j]) {
                j--;
            }
            swap(nums, i, j);
        }
        reverse(nums, i + 1);
    }

    public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public void reverse(int[] nums, int start) {
        int left = start, right = nums.length - 1;
        while (left < right) {
            swap(nums, left, right);
            left++;
            right--;
        }
    }

}